package com.hs.srm.admin.modules.abnormalquality.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hs.srm.admin.modules.abnormalquality.entity.AbnormalAuditRecordEntity;
import com.hs.srm.admin.modules.abnormalquality.entity.AbnormalQualityEntity;
import com.hs.srm.admin.modules.abnormalquality.service.AbnormalAuditRecordService;
import com.hs.srm.admin.modules.abnormalquality.service.AbnormalQualityService;
import com.hs.srm.admin.modules.notice.dictionary.NoticeKind;
import com.hs.srm.admin.modules.notice.service.NoticeMainInfoService;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.admin.modules.vendor.entity.VendorInfoEntity;
import com.hs.srm.admin.modules.vendor.service.VendorService;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.config.SysConfig;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.base.modules.sys.service.SysUserService;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.hs.srm.tools.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 品质异常单
 *
 * @author ych
 * @since 2020-04-07 15:02:27
 */
@RestController
@RequestMapping("/abnormalQuality")
public class AbnormalQualityController extends AbstractController {

    @Autowired
    private AbnormalQualityService abnormalQualityService;

    @Autowired
    private VendorService vendorService;

    @Autowired
    private NoticeMainInfoService noticeMainInfoService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private AbnormalAuditRecordService auditRecordService;

    /**
     * 查询列表
     *
     * @param params
     * @return
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        String userName = this.getUser().getUsername();
        PageUtils page;
        VendorInfoEntity vendorInfoEntity = vendorService.selectByVendorCode(userName);
        //当前用户为供应商
        if (ObjectUtil.isNotNull(vendorInfoEntity)) {
            //将sapCode放入map，查询条件
            params.put("sapCode", userName);
        }
        page = abnormalQualityService.queryPage(params);

        return R.ok(page);
    }

    /**
     * 品质异常单详情页面
     *
     * @return
     */
    @RequestMapping("/details")
    public ModelAndView declarationDetails(@RequestParam("pkId") String pkId) {
        ModelAndView modelAndView = new ModelAndView("modules/abnormal/abnormal_detail");
        AbnormalQualityEntity abnormalQualityEntity = abnormalQualityService.selectById(pkId);
        modelAndView.addObject("abnormalQualityEntity", abnormalQualityEntity);
        return modelAndView;
    }

    /**
     * 品质异常新增页面
     *
     * @return
     */
    @RequiresPermissions("abnormal:add")
    @GetMapping("/addAbnormal")
    public ModelAndView addAbnormal() {
        String name = this.getUser().getName();
        ModelAndView modelAndView = new ModelAndView("modules/abnormal/abnormal_add");
        modelAndView.addObject("name", name);
        return modelAndView;
    }

    @SysLog("新增品质异常")
    @PostMapping("/addAbnormal")
    public R addAbnormal(AbnormalQualityEntity entity, HttpServletRequest request) throws IOException, ServletException {
        //文件保存路径
        String fileDir = SysConfig.getUploadPath() + "/abnormalquality/";
        Part part = request.getPart("attach");
        if (part != null) {
            //添加时间后缀 _yyyyMMddHHmmss
            String fileName = FileUtils.addDateTimeSuffix(part.getSubmittedFileName());
            FileUtils.fileUpload(fileDir, fileName, part);
            entity.setSqeAttach("/abnormalquality/" + fileName);
        }
        //创建人、创建时间
        entity.setCreateDate(new Date());
        entity.setCreator(this.getUser().getName());

        abnormalQualityService.insert(entity);
        //通知供应商
        SysUserEntity vendorUser = sysUserService.selectOne(new EntityWrapper<SysUserEntity>()
                .eq("username", entity.getVendorCode()));
        String content = "您有待处理的品质异常单！";
        noticeMainInfoService.saveNotice(vendorUser.getUserId(), content);

        //添加操作记录
        AbnormalAuditRecordEntity auditRecordEntity = new AbnormalAuditRecordEntity(entity.getAuditResult(),
                entity.getPkId(), entity.getCreator(), entity.getCreateDate());
        auditRecordService.insert(auditRecordEntity);
        return R.ok();
    }

    /**
     * 供应商编辑异常单页面
     *
     * @return
     */
    @RequiresPermissions("abnormal:edit")
    @RequestMapping("/vendorEdit")
    public ModelAndView vendorEdit(@RequestParam("pkId") String pkId) {
        ModelAndView modelAndView = new ModelAndView("modules/abnormal/abnormal_edit");
        AbnormalQualityEntity abnormalQuality = abnormalQualityService.selectById(pkId);
        modelAndView.addObject("abnormalQuality", abnormalQuality);
        //当前编辑人是供应商
        modelAndView.addObject("editor", "vendor");
        return modelAndView;
    }

    /**
     * 保存供应商编辑的数据
     *
     * @return
     */
    @SysLog("异常单编辑")
    @RequiresPermissions("abnormal:edit")
    @RequestMapping("/saveEdit")
    public R saveEdit(AbnormalQualityEntity entity, HttpServletRequest request) throws IOException, ServletException {
        //文件保存路径
        String fileDir = SysConfig.getUploadPath() + "/abnormalquality/";
        Part part = request.getPart("attach");
        if (part != null) {
            //添加时间后缀 _yyyyMMddHHmmss
            String fileName = FileUtils.addDateTimeSuffix(part.getSubmittedFileName());
            FileUtils.fileUpload(fileDir, fileName, part);
            entity.setVendorAttach("/abnormalquality/" + fileName);
        }
        //供应商提交保存数据，状态修改为审核中
        entity.setAuditResult(AbnormalQualityEntity.SHZ);
        boolean row = abnormalQualityService.updateById(entity);
        if (row) {
            //通知品质专员
            String content = entity.getVendorName() + " 已填写品质异常单 ！";
            abnormalQualityService.sendNotice(NoticeKind.KindEnum.PZYCD, content);
            //添加操作记录
            AbnormalAuditRecordEntity auditRecordEntity = new AbnormalAuditRecordEntity(entity.getAuditResult(),
                    entity.getPkId(), this.getUser().getName(), new Date());
            auditRecordService.insert(auditRecordEntity);
        } else {
            return R.error();
        }
        return R.ok();
    }

    /**
     * 异常单审核页
     *
     * @return
     */
    @RequiresPermissions("abnormal:audit")
    @RequestMapping("/sqeAudit")
    public ModelAndView sqeAudit(@RequestParam("pkId") String pkId) {
        ModelAndView modelAndView = new ModelAndView("modules/abnormal/abnormal_edit");
        AbnormalQualityEntity abnormalQuality = abnormalQualityService.selectById(pkId);
        modelAndView.addObject("abnormalQuality", abnormalQuality);
        //当前编辑人是sqe
        modelAndView.addObject("editor", "sqe");
        return modelAndView;
    }

    @SysLog("SQE审核异常单")
    @RequestMapping("/saveAudit")
    public R saveAudit(AbnormalQualityEntity abnormal) {
        boolean b = abnormalQualityService.updateById(abnormal);
        if (b) {
            //通知供应商
            SysUserEntity vendorUser = sysUserService.selectOne(new EntityWrapper<SysUserEntity>()
                    .eq("username", abnormal.getVendorCode()));
            String content = "您的品质异常单已被审核 " + (abnormal.getAuditResult().equals(AbnormalQualityEntity.TG) ? "通过" : "驳回！");
            noticeMainInfoService.saveNotice(vendorUser.getUserId(), content);

            //添加操作记录
            AbnormalAuditRecordEntity auditRecordEntity = new AbnormalAuditRecordEntity(abnormal.getAuditResult()
                    , abnormal.getPkId(), this.getUser().getName(), new Date(), abnormal.getAuditComment());
            auditRecordService.insert(auditRecordEntity);
        }
        return R.ok();
    }

    /**
     * sqe异常单操作记录
     *
     * @return
     */
    @GetMapping("/record/{pkId}")
    public R record(@PathVariable("pkId") String pkId) {
        List<AbnormalAuditRecordEntity> abnormalAuditRecordEntity = auditRecordService.selectList(new EntityWrapper<AbnormalAuditRecordEntity>()
                .eq("abnormal_id", pkId)
                .orderBy("create_time"));
        return R.ok(abnormalAuditRecordEntity);
    }

    /**
     * 根据id下载sqe附件
     */
    @RequestMapping("/downloadFileById")
    public void downloadFileById(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        AbnormalQualityEntity abnormalQualityEntity = abnormalQualityService.selectById(id);
        File file = new File(SysConfig.getUploadPath() + abnormalQualityEntity.getSqeAttach());
        FileUtils.fileDownload(file, request, response);
    }

    /**
     * 根据id下载供应商附件
     */
    @RequestMapping("/downloadVendorFileById")
    public void downloadvendorFileById(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        AbnormalQualityEntity abnormalQualityEntity = abnormalQualityService.selectById(id);
        File file = new File(SysConfig.getUploadPath() + abnormalQualityEntity.getVendorAttach());
        FileUtils.fileDownload(file, request, response);
    }

}